import 'dart:async';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import '../models/article.dart';
import '../models/audio.dart';
import '../services/api_service.dart';
import '../config/app_config.dart';

/// 音频播放状态管理
class AudioProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  final AudioPlayer _audioPlayer = AudioPlayer();
  
  // 当前播放的资讯
  Article? _currentArticle;
  
  // 当前语言（cn/en）
  String _currentLanguage = 'cn';
  
  // 播放状态
  bool _isPlaying = false;
  Duration _currentTime = Duration.zero;
  Duration _duration = Duration.zero;
  double _playbackRate = 1.0;
  
  // 时间戳数据
  List<TimestampItem> _timestamps = [];
  
  // 当前高亮的句子索引
  int _currentSentenceIndex = -1;
  
  // 是否正在加载
  bool _isLoading = false;
  
  StreamSubscription? _positionSubscription;
  StreamSubscription? _durationSubscription;
  StreamSubscription? _playerStateSubscription;
  
  // Getters
  Article? get currentArticle => _currentArticle;
  String get currentLanguage => _currentLanguage;
  bool get isPlaying => _isPlaying;
  Duration get currentTime => _currentTime;
  Duration get duration => _duration;
  double get playbackRate => _playbackRate;
  List<TimestampItem> get timestamps => _timestamps;
  int get currentSentenceIndex => _currentSentenceIndex;
  bool get isLoading => _isLoading;
  
  String get formattedCurrentTime => _formatDuration(_currentTime);
  String get formattedDuration => _formatDuration(_duration);
  double get progress => _duration.inMilliseconds > 0 
      ? _currentTime.inMilliseconds / _duration.inMilliseconds * 100
      : 0;
  
  AudioProvider() {
    _initAudioPlayer();
  }
  
  /// 初始化音频播放器
  void _initAudioPlayer() {
    // 监听播放位置
    _positionSubscription = _audioPlayer.positionStream.listen((position) {
      _currentTime = position;
      _updateCurrentSentence();
      notifyListeners();
    });
    
    // 监听时长
    _durationSubscription = _audioPlayer.durationStream.listen((duration) {
      if (duration != null) {
        _duration = duration;
        notifyListeners();
      }
    });
    
    // 监听播放状态
    _playerStateSubscription = _audioPlayer.playerStateStream.listen((state) {
      _isPlaying = state.playing;
      
      // 播放结束
      if (state.processingState == ProcessingState.completed) {
        _isPlaying = false;
        _currentTime = Duration.zero;
        _currentSentenceIndex = -1;
        // 停止播放并重置到开头
        _audioPlayer.pause();
        _audioPlayer.seek(Duration.zero);
        debugPrint('音频播放完成，已暂停并重置到开头');
      }
      
      notifyListeners();
    });
  }
  
  /// 初始化音频
  Future<void> initAudio(int articleId, Article article, String language) async {
    try {
      _isLoading = true;
      _currentArticle = article;
      _currentLanguage = language;
      notifyListeners();
      
      // 获取音频信息（后端返回包含OSS签名URL的音频信息）
      final audioRes = await _apiService.getAudioInfo(articleId, language);
      final audioData = Audio.fromJson(audioRes.data['data']);
      
      if (audioData.audioId == 0) {
        throw Exception('音频资源不可用');
      }
      
      // 检查是否有音频URL
      if (audioData.audioUrl == null || audioData.audioUrl!.isEmpty) {
        throw Exception('音频URL不可用');
      }
      
      debugPrint('加载音频URL: ${audioData.audioUrl}');
      
      // 所有平台都使用签名URL直接播放（支持流式加载和Range请求）
      await _audioPlayer.setUrl(audioData.audioUrl!);
      
      // 设置播放速度
      await _audioPlayer.setSpeed(_playbackRate);
      
      // 设置时间戳
      if (audioData.timestamps != null) {
        _timestamps = audioData.timestamps!;
      }
      
      _isLoading = false;
      notifyListeners();
      
      debugPrint('音频加载成功，支持流式播放');
    } catch (e) {
      debugPrint('初始化音频失败: $e');
      _isLoading = false;
      notifyListeners();
      rethrow;
    }
  }
  
  /// 播放/暂停
  Future<void> togglePlay() async {
    if (_isPlaying) {
      await _audioPlayer.pause();
    } else {
      await _audioPlayer.play();
    }
  }
  
  /// 播放
  Future<void> play() async {
    await _audioPlayer.play();
  }
  
  /// 暂停
  Future<void> pause() async {
    await _audioPlayer.pause();
  }
  
  /// 跳转到指定时间
  Future<void> seekTo(Duration position) async {
    await _audioPlayer.seek(position);
  }
  
  /// 快退15秒
  Future<void> rewind() async {
    final newPosition = _currentTime - Duration(seconds: AppConfig.audioSeekSeconds);
    await seekTo(newPosition < Duration.zero ? Duration.zero : newPosition);
  }
  
  /// 快进15秒
  Future<void> forward() async {
    final newPosition = _currentTime + Duration(seconds: AppConfig.audioSeekSeconds);
    await seekTo(newPosition > _duration ? _duration : newPosition);
  }
  
  /// 设置播放速度
  Future<void> setPlaybackRate(double rate) async {
    _playbackRate = rate;
    await _audioPlayer.setSpeed(rate);
    notifyListeners();
  }
  
  /// 更新当前句子（二分查找）
  void _updateCurrentSentence() {
    if (_timestamps.isEmpty) {
      _currentSentenceIndex = -1;
      return;
    }
    
    final currentSeconds = _currentTime.inMilliseconds / 1000;
    int index = -1;
    
    for (int i = 0; i < _timestamps.length; i++) {
      final ts = _timestamps[i];
      if (currentSeconds >= ts.start && currentSeconds <= ts.end) {
        index = i;
        break;
      }
    }
    
    if (index != _currentSentenceIndex) {
      _currentSentenceIndex = index;
    }
  }
  
  /// 点击句子跳转
  Future<void> jumpToSentence(int index) async {
    if (index >= 0 && index < _timestamps.length) {
      final time = Duration(milliseconds: (_timestamps[index].start * 1000).toInt());
      await seekTo(time);
      if (!_isPlaying) {
        await play();
      }
    }
  }
  
  /// 切换语言
  Future<void> switchLanguage(String language, int articleId) async {
    _currentLanguage = language;
    notifyListeners();
    
    // 重新加载音频
    if (_currentArticle != null) {
      await initAudio(articleId, _currentArticle!, language);
    }
  }
  
  /// 格式化时长
  String _formatDuration(Duration duration) {
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
    final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
    
    // 如果超过1小时，显示 HH:MM:SS 格式
    if (hours > 0) {
      return '$hours:$minutes:$seconds';
    }
    // 否则显示 MM:SS 格式
    return '$minutes:$seconds';
  }
  
  /// 重置
  void reset() {
    _audioPlayer.stop();
    _currentArticle = null;
    _currentLanguage = 'cn';
    _isPlaying = false;
    _currentTime = Duration.zero;
    _duration = Duration.zero;
    _timestamps = [];
    _currentSentenceIndex = -1;
    _isLoading = false;
    notifyListeners();
  }
  
  @override
  void dispose() {
    _positionSubscription?.cancel();
    _durationSubscription?.cancel();
    _playerStateSubscription?.cancel();
    _audioPlayer.dispose();
    super.dispose();
  }
}

